package cn.promonkey.core.runner;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cn.promonkey.api.student.entity.Student;
import cn.promonkey.api.student.service.StudentService;
import cn.promonkey.api.teacher.entity.Teacher;
import cn.promonkey.api.teacher.service.TeacherService;
import cn.promonkey.api.user.entity.User;
import cn.promonkey.api.user.service.UserService;
import cn.promonkey.core.toolkit.HttpClientUtils;
import cn.promonkey.core.utils.RedisUtils;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class DataLoadingRunner implements CommandLineRunner {

	@Value("${weixin.appId}")
	private String appIdValue;
	
	@Value("${weixin.appSecret}")
	private String appSecretValue;
	
	@Autowired 
	private RedisUtils redisUtilsValue;
	
	@Autowired
	private UserService userServiceValue;
	
	@Autowired
	private TeacherService teacherServiceValue;
	
	@Autowired
	private StudentService studentServiceValue;
	

	private static String appId;
	
	private static String appSecret;
	
	private static RedisUtils redisUtils;
	
	private static UserService userService;
	
	private static TeacherService teacherService;
	
	private static StudentService studentService;	
	
	@PostConstruct
	public void init() {
		appId = appIdValue;
		appSecret = appSecretValue;
		redisUtils = redisUtilsValue;
		userService = userServiceValue;
		teacherService = teacherServiceValue;
		studentService = studentServiceValue;
	}

	//每天定时执行
	//@Scheduled(cron = "0 30 8 * * *")
	@Scheduled(cron = "0 0 0/1 * * ?")
	public void Tasks() throws Exception {
		Thread thread = new Thread(myRunnable);
		thread.start();
	}
	
	//每天定时执行
	//@Scheduled(cron = "0 30 8 * * *")
	@Scheduled(cron = "0 0/1 * * * ?")
	public void Tasks2() throws Exception {
		Thread thread2 = new Thread(myRunnable2);
		thread2.start();
	}

	//启动时执行
	@Override
	public void run(String... args) throws Exception {
		Thread thread = new Thread(myRunnable);
		thread.start();
		Thread thread2 = new Thread(myRunnable2);
		thread2.start();
	}
	
	Runnable myRunnable = new Runnable() {
		@Override
		public void run() {
			log.info("启动预加载数据(DataLoadingRunner)...{}");
			
			String rtnStr = HttpClientUtils.doGetRequest("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appSecret, null, null);

	  		JSONObject rtnJSON = JSONObject.parseObject(rtnStr);
	  		
	  		String access_token = rtnJSON.getString("access_token");
			
	  		redisUtils.set("weixin_access_token", access_token);

		}
	};
	Runnable myRunnable2 = new Runnable() {
		@Override
		public void run() {
			List<User> userList = userService.list();
			for(User user:userList) {
				redisUtils.hset("WEIXIN_OPENID",user.getUserId().toString(),user.getOpenid());
				redisUtils.hset("USERID_BUSINESSID",user.getUserId().toString(),user.getBusinessId());
			}
			//根据businessId区分企业用户
			Map<Long, List<User>> usersMap = userList.stream().collect(Collectors.groupingBy(user -> user.getBusinessId()));
						for(Entry<Long, List<User>> users:usersMap.entrySet()) {
				Map<Long, String> userMap = users.getValue().stream().collect(Collectors.toMap(User::getUserId, User::getName)); 
				redisUtils.hset("USER_ID_NAME", users.getKey().toString(), userMap);
				List<User> userss =  users.getValue().stream().filter(user -> user.getPhone()!=null).collect(Collectors.toList());
				redisUtils.hset("USER_ID_LIST", users.getKey().toString(), userss);			}	
			
			QueryWrapper<Teacher> collegeWrapper = new QueryWrapper<>();
			collegeWrapper.select("distinct business_id as businessId,college as college").lambda();
			List<Teacher> collegeList = teacherService.list(collegeWrapper);
			Map<Long, List<Teacher>> collegeMap = collegeList.stream().collect(Collectors.groupingBy(user -> user.getBusinessId()));
			for(Entry<Long, List<Teacher>> college:collegeMap.entrySet()) {
				String[] colleges = college.getValue().stream().map(Teacher::getCollege).toArray(String[]::new);
				redisUtils.hset("TEACHER_COLLEGE", college.getKey().toString(), JSONObject.toJSONString(colleges));
			}
			
			QueryWrapper<Teacher> departmentWrapper = new QueryWrapper<>();
			departmentWrapper.select("distinct business_id as businessId,department as department").lambda();
			List<Teacher> departmentList = teacherService.list(departmentWrapper);
			Map<Long, List<Teacher>> departmentMap = departmentList.stream().collect(Collectors.groupingBy(user -> user.getBusinessId()));
			for(Entry<Long, List<Teacher>> department:departmentMap.entrySet()) {
				String[] departments = department.getValue().stream().map(Teacher::getDepartment).toArray(String[]::new);
				redisUtils.hset("TEACHER_DEPARTMENT", department.getKey().toString(), JSONObject.toJSONString(departments));
			}
			
			QueryWrapper<Teacher> majorWrapper = new QueryWrapper<>();
			majorWrapper.select("distinct business_id as businessId,major as major").lambda();
			List<Teacher> majorList = teacherService.list(majorWrapper);
			Map<Long, List<Teacher>> majorMap = majorList.stream().collect(Collectors.groupingBy(user -> user.getBusinessId()));
			for(Entry<Long, List<Teacher>> major:majorMap.entrySet()) {
				String[] majors = major.getValue().stream().map(Teacher::getMajor).toArray(String[]::new);
				redisUtils.hset("TEACHER_MAJOR", major.getKey().toString(), JSONObject.toJSONString(majors));
			}
			//查询所有教师并返回
			List<Teacher> teacherList = teacherService.list();
			Map<Long, List<Teacher>> teacherMap = teacherList.stream().collect(Collectors.groupingBy(user -> user.getBusinessId()));
			for(Entry<Long, List<Teacher>> teacher:teacherMap.entrySet()) {
				redisUtils.hset("TEACHER_ALL", teacher.getKey().toString(), teacher.getValue());
			}
			
			QueryWrapper<Student> gradeWrapper = new QueryWrapper<>();
			gradeWrapper.select("distinct business_id as businessId,tas_grade as tasGrade").lambda();
			List<Student> gradeList = studentService.list(gradeWrapper);
			Map<Long, List<Student>> gradeMap = gradeList.stream().collect(Collectors.groupingBy(user -> user.getBusinessId()));
			for(Entry<Long, List<Student>> grade:gradeMap.entrySet()) {
				String[] grades = grade.getValue().stream().map(Student::getTasGrade).toArray(String[]::new);
				redisUtils.hset("STUDENT_GRADE", grade.getKey().toString(), JSONObject.toJSONString(grades));
			}
			QueryWrapper<Student> classWrapper = new QueryWrapper<>();
			classWrapper.select("distinct business_id as businessId,tas_class as tasClass").lambda();
			List<Student> classList = studentService.list(classWrapper);
			Map<Long, List<Student>> classMap = classList.stream().collect(Collectors.groupingBy(user -> user.getBusinessId()));
			for(Entry<Long, List<Student>> class1:classMap.entrySet()) {
				String[] classs = class1.getValue().stream().map(Student::getTasClass).toArray(String[]::new);
				redisUtils.hset("STUDENT_CLASS", class1.getKey().toString(), JSONObject.toJSONString(classs));
			}
			
			QueryWrapper<Student> majorsWrapper = new QueryWrapper<>();
			majorsWrapper.select("distinct business_id as businessId,major as major").lambda();
			List<Student> majorsList = studentService.list(majorsWrapper);
			Map<Long, List<Student>> majorsMap = majorsList.stream().collect(Collectors.groupingBy(user -> user.getBusinessId()));
			for(Entry<Long, List<Student>> major:majorsMap.entrySet()) {
				String[] majors = major.getValue().stream().map(Student::getMajor).toArray(String[]::new);
				redisUtils.hset("STUDENT_MAJOR", major.getKey().toString(), JSONObject.toJSONString(majors));
			}
			
			//查询所有学生并返回
			List<Student> studentList = studentService.list();
			Map<Long, List<Student>> studentMap = studentList.stream().collect(Collectors.groupingBy(user -> user.getBusinessId()));
			for(Entry<Long, List<Student>> student:studentMap.entrySet()) {
				redisUtils.hset("STUDENT_ALL", student.getKey().toString(), student.getValue());
			}

		}
	};

}
